package com.able.concurrency.t3;

import java.util.concurrent.TimeUnit;

/**
 * @author abel.he
 * @data 2018/8/19 15:48
 * @describe ThreadLocal 可以理解为map 其中的key为Thread.getCurrentThread() value为线程需要保存的变量
 * ThreadLocal.set(value)  ==> map.put(Thread.currentThread(), value)
 * ThreadLocal.get() ==> map.get(Thread.currentThread())
 * 内存问题，并发量高的时候会存在内存溢出
 * 使用ThreadLocal注意资源回收问题，每个线程结束之前，将当前线程保存的线程变量一定要删除
 * ThreadLocal.remove()
 */
public class TestThreadLocal {

    static ThreadLocal<String> threadLocal = new ThreadLocal();

    static String name = "zhangsan";

    public static void main(String[] args) {

        final TestThreadLocal testThreadLocal = new TestThreadLocal();

        new Thread(new Runnable() {
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(4);
                    System.out.println(name);
                    System.out.println(threadLocal.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            public void run() {
                name = "lisi";
                threadLocal.set("haha");
            }
        }).start();

    }

}
